import {constantRouterMap, asyncRouterMap} from '@/router/index'

/**
 * 当前路由是否有权限
 * @param menus 已经拥有权限
 * @param item 系统路由
 */
function hasPermission (menus, item) {
  // 后台定义的菜单以及属性
  const menu = getMenu(menus, item.name)
  // 若在本地查找不到
  if (menu == null) {
    return false
  } else {
    return true
  }
}

/**
 * 查询加载下来的菜单里面的内容，用于替换
 * @param menu
 * @param name
 */
function getMenu (menu, name) {
  for (let i = 0; i < menu.length; i++) {
    let item = menu[i]
    if (name === item.name) {
      return item
    }
  }
  return null
}

const permission = {
  state: {
    // 用户所需要的路由
    routers: constantRouterMap,
    // 添加的路由
    addRouters: []
  },
  mutations: {
    SET_ROUTER: (store, router) => {
      store.addRouters = router
      store.routers = constantRouterMap.concat(router)
    }
  },
  actions: {
    // 查询的菜单进行加载
    GenerateRouter ({commit}, data) {
      return new Promise(resolve => {
        let {menus} = data
        let result = asyncRouterMap.filter(item => {
          if (hasPermission(menus, item)) {
            item.children = item.children.filter(child => {
              if (hasPermission(menus, child)) {
                return child
              }
            })
            return item
          }
        })
        commit('SET_ROUTER', result)
        resolve(result)
      })
    }
  }
}

export default permission
